<?php

require_once(WSB_MODULES_PATH .'sherpa/models/BaseGateway.php');
require_once(WSB_MODULES_PATH .'sherpa/models/Orders.php');

class Sherpa_Model_OrderGateway extends Sherpa_Model_BaseGateway
{

	/**
	 * @return Sherpa_Model_Orders
	 */
	public function fetchOrders()
	{
		$select = $this->getDbSelect();
		$select->from(array('b' => 'sherpa_orders'));
		return new Sherpa_Model_Orders($select->query()->fetchAll());
	}

	/**
	 * @return Sherpa_Model_Orders
	 */
	public function fetchFeuserOrders()
	{
		$auth = WSB_Auth_Frontend::getInstance();
		if($auth->hasIdentity()) {
			$feuser = $auth->getIdentity();
			$select = $this->getDbSelect();
			$select->from(array('b' => 'sherpa_orders'));
			$select->where('feuserId=?', $feuser->id);
			return new Sherpa_Model_Orders($select->query()->fetchAll());
		} else {
			return new Sherpa_Model_Orders(array());
		}
	}

	/**
	 * @param array $order
	 * @return integer Last insert ID
	 */
	public function addOrder(Sherpa_Model_Order $order)
	{
		$data = $order->getData();
		$data['orderDate'] = new Zend_Db_Expr('NOW()');
		$data['modified'] = new Zend_Db_Expr('NOW()');
		$data['created'] = new Zend_Db_Expr('NOW()');
		$db = $this->getDb();
		$db->insert('sherpa_orders', $data);
		return $db->lastInsertId('sherpa_orders');
	}

	/**
	 * @param array $data
	 * @param integer $id
	 * @return integer
	 */
	public function updateOrder(array $data, $id)
	{
		$db = $this->getDb();
		$data['modified'] = new Zend_Db_Expr('NOW()');
		return $db->update('sherpa_orders', $data, 'id=' . $id);
	}

}
